package com.liu.netty5.server;

import com.liu.netty5.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * Created by Administrator on 2019/8/28 0028.
 */
public class Server {

    public static void main(String[] args) {

        ServerBootstrap  bootstrap = new ServerBootstrap();

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {

//       设置 工作线程
            bootstrap.group(boss,worker);

            bootstrap.channel(NioServerSocketChannel.class);

            bootstrap.childHandler(new ChannelInitializer<Channel>() {


                @Override
                protected void initChannel(Channel channel) throws Exception {
                    channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
                    channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
                    channel.pipeline().addLast(new ServerHandler());

                }
            });

            bootstrap.option(ChannelOption.SO_BACKLOG,1024);// 服务端排队队列
            bootstrap.option(ChannelOption.TCP_NODELAY,true);// TCP 无延时
            bootstrap.option(ChannelOption.SO_KEEPALIVE,true);// 清除死链接，维持活跃的
//    绑定通讯端口
            ChannelFuture future = bootstrap.bind(10040);
//    sout
            System.out.println("服务端启动！！！");
            future.channel().closeFuture().sync();

        }catch (Exception e){

        }finally {
            //            优雅关闭
            boss.shutdownGracefully();
//            优雅关闭
            worker.shutdownGracefully();
        }




    }


}
